<?php
class Admin_ProductController extends My_Controller_Action {
	private $_model = '';
	private $_moduleName = '';
	private $_controllerName = '';
	private $_actionName = '';
	private $_actionMain = '';
	private $_params = array ();
	private $_userId = '';

	public function init() {
		$template_path = TEMPLATE_PATH . "/admin";
		$this->loadTemplate ( $template_path, 'template.ini', 'template' );
		$this->view->headScript ()
			->appendFile ( TEMPLATE_URL . '/admin/js/ckeditor/ckeditor.js' );
		$this->_model = new Admin_Model_Product ();
		$this->_moduleName = $this->_request->getModuleName (); //
		$this->_controllerName = $this->_request->getControllerName (); //
		$this->_actionName = $this->_request->getActionName ();
		$this->_params = $this->_request->getParams ();
		$this->_actionMain = '/' . $this->_moduleName . '/' . $this->_controllerName . '/index';
		
		
		$this->view->params = $this->_params;
		$this->view->controllerName = $this->_controllerName;
		
		$auth = Zend_Auth::getInstance ();
		$infoUser = $auth->getIdentity ();
		$this->_userId = $infoUser ['userId'];
		
		My_Auth_User::authenticate();		
	}

	public function indexAction() {
		//My_Auth_User::allow($this->_request);
		
		$this->_redirect ( "/{$this->_moduleName}/{$this->_controllerName}/show-all" );
	}

	public function showAllAction() {
		$product = $this->_model->getProduct ();
		
		$this->view->product = $product;
	}

	public function addAction() {
		$data = $this->_request->getPost ();
		$form = new Admin_Form_Product ();
		
		$categoryModel = new Admin_Model_Category ();
		$categorys = $categoryModel->getFetchPairs ( array ('parentId' => 0), array ('task' => 'by-parent') );
		
		if ($this->_request->isPost ()) {
			$valid = new Admin_Form_Validators_ProductValid ( $data );
			
			if ($form->isValid ( $data ) && $valid->isValid ()) {
				$data = $form->getValues ();	
			
				$data ['categoryId'] = end($this->_params ['categoryId']);
				$data ['categorys'] = implode(',', $this->_params ['categoryId']);
				$data ['createdBy'] = $this->_userId;
				
				$db = Zend_Db_Table::getDefaultAdapter();
				$db->beginTransaction();
				
				try {
					$fileUpload = new My_File_Upload();					
					$data['image'] = $fileUpload->upload('image', 'products', array('task' => 'rename', 'isThumb' => TRUE));

					$productId = $this->_model->addItem ( $data );
					$optionDetail = $this->_params['optionDetail'];
					
					$option = $this->_params['option'];
					
					$imageModel = new Admin_Model_Image();
					$tmpModel = new Admin_Model_Tmp();
					$productFeatureDetailModel = new Admin_Model_ProductFeatureDetail();
					
					foreach($optionDetail as $item){
						if(isset($item['featureDetailId']) && $item['featureDetailId'] != null){
							$dataOptionDetail = array(
								'productId' => $productId,
								'featureDetailId' => $item['featureDetailId'],
								'pricePlus' => $item['pricePlus'],
								'amountFeatureDetail' => $item['amountFeatureDetail']
							);
							$productFeatureDetailId = $productFeatureDetailModel->addItem ( $dataOptionDetail );
							
							$tmps = $tmpModel->getTmp(array('task' => 'admin-featureDetail'), array('userId' => $this->_userId, 'featureDetailId' => $item['featureDetailId']));
							foreach($tmps as $itemTmp){
								$dataImage = array(
									'productId' => $productId,
									'productFeatureDetailId' => $productFeatureDetailId,
									'name' => $itemTmp['fileName']
								);
								$imageModel->addItem($dataImage);
								$tmpModel->deleteItem($itemTmp['id']);
							}
						}
					}
					
					foreach($option as $item){
						$dataOption = array(
							'productId' => $productId,
							'featureDetailId' => $item
						);
						$productFeatureDetailId = $productFeatureDetailModel->addItem ( $dataOption );						
					}
					
					$db->commit();
				} catch (Exception $e) {
					$db->rollBack();
					throw $e;
				}
				
				if ($productId) {
					if (isset ( $this->_params ['btnSave'] )) {
						$this->view->popupMessage = $this->_helper->popupMessage ( MESS_ADD, $this->_actionMain );
					} elseif (isset ( $this->_params ['btnSaveAdd'] )) {
						$this->_redirect ( "/{$this->_moduleName}/{$this->_controllerName}/{$this->_actionName}" );
					}
				}
			} else {
				$this->view->error = $valid->messages;
			}
		}
		$this->view->form = $form;
		$this->view->category = $categorys;
		
	}

	public function editAction() {
		$productId = $this->_params ['id'];
		
		if ($this->_request->isPost ()) {
			$data = $this->_request->getPost ();
		} else {
			$data = $this->_model->getProductOne ( $productId );
		}
		
		$categoryModel = new Admin_Model_Category ();
		
		if($data['categorys'] != null){
			$categoryPath = '0,'.$data['categorys'];
		}
		
		$categorys = $categoryModel->getCategorys ($categoryPath, array('task' => 'by-parent-in'));
		
		$arrCategory = null;
		foreach($categorys as $key => $value){
			$arrCategory[$value['level']][] = $value;
		}
		ksort($arrCategory);
		
		$featureDetailModel = new Admin_Model_FeatureDetail();
		$featureDetails = $featureDetailModel->getFeatureDetail($data['id'], array('task' => 'admin-product'));
		
		$arrFeatureDetail = null;
    	foreach($featureDetail as $key => $value){
    		$arrFeatureDetail[$value['categoryId']]['CategoryName'] = $value['CategoryName'];
    		$arrFeatureDetail[$value['categoryId']][] = $value;
    	}
    	
		$form = new Admin_Form_Product ();
		
		if ($this->_request->isPost ()) {
			$valid = new Admin_Form_Validators_ProductValid ( $data );
			if ($form->isValid ( $data ) && $valid->isValid ()) {
				$data = $form->getValues ();				
				$data ['categoryId'] = end($this->_params ['categoryId']);
				$data ['categorys'] = implode(',', $this->_params ['categoryId']);
				$data ['createdBy'] = $this->_userId;
				
				$db = Zend_Db_Table::getDefaultAdapter();
				$db->beginTransaction();
				
				try {
					$fileUpload = new My_File_Upload();					
					$data['image'] = $fileUpload->upload('image', 'products', array('task' => 'rename', 'isThumb' => TRUE));
					
					$productId = $this->_model->updateItem ( $productId, $data );
					$optionDetail = $this->_params['optionDetail'];
					$option = $this->_params['option'];
					
					$imageModel = new Admin_Model_Image();
					$tmpModel = new Admin_Model_Tmp();
					$productFeatureDetailModel = new Admin_Model_ProductFeatureDetail();
					
					foreach($optionDetail as $item){
						if(isset($item['featureDetailId']) && $item['featureDetailId'] != null){
							$dataOptionDetail = array(
								'productId' => $productId,
								'featureDetailId' => $item['featureDetailId'],
								'pricePlus' => $item['pricePlus'],
								'amountFeatureDetail' => $item['amountFeatureDetail']
							);
							$productFeatureDetailId = $productFeatureDetailModel->addItem ( $dataOptionDetail );
							
							$tmps = $tmpModel->getTmp(array('task' => 'admin-featureDetail'), array('userId' => $this->_userId, 'featureDetailId' => $item['featureDetailId']));
							foreach($tmps as $itemTmp){
								$dataImage = array(
									'productId' => $productId,
									'productFeatureDetailId' => $productFeatureDetailId,
									'name' => $itemTmp['fileName']
								);
								$imageModel->addItem($dataImage);
								$tmpModel->deleteItem($itemTmp['id']);
							}
						}
					}
					
					foreach($option as $item){
						$dataOption = array(
							'productId' => $productId,
							'featureDetailId' => $item
						);
						$productFeatureDetailId = $productFeatureDetailModel->addItem ( $dataOption );						
					}
					
					$db->commit();
				} catch (Exception $e) {
					$db->rollBack();
					throw $e;
				}
				
				if ($productId) {
					if (isset ( $this->_params ['btnSave'] )) {
						$this->view->popupMessage = $this->_helper->popupMessage ( MESS_UPDATE, $this->_actionMain );
					} elseif (isset ( $this->_params ['btnSaveAdd'] )) {
						$this->_redirect ( "/{$this->_moduleName}/{$this->_controllerName}/{$this->_actionName}" );
					}
				}
			} else {
				$this->view->error = $valid->messages;
			}
		}
		
		$this->view->arrCategory = $arrCategory;
		$this->view->arrFeatureDetail = $arrFeatureDetail;
		$form->populate ( $data );
		$this->view->form = $form;
		$this->view->data = $data;
		$this->view->headScript ()
					->appendFile ( TEMPLATE_URL . '/admin/js/ckeditor/ckeditor.js' );
	}

	function ajaxEditProductAction() {
		$template_path = TEMPLATE_PATH . "/admin";
		$this->loadTemplate ( $template_path, 'template.ini', 'ajax' );
		$this->_helper->viewRenderer->setNoRender ();
		
		$categoryId = $this->_params ['id'];
		$field = $this->_params ['field'];
		$value = $this->_params ['value'];
		
		$data [$field] = $value;
		
		$result = array (
				'result' => $this->_model->updateItem ( $categoryId, $data ),
				'value' => $value 
		);
		echo json_encode ( $result );
		die ();
	}

	function ajaxDeleteProductAction() {
		$template_path = TEMPLATE_PATH . "/admin";
		$this->loadTemplate ( $template_path, 'template.ini', 'ajax' );
		$this->_helper->viewRenderer->setNoRender ();
		
		$productModel = new Admin_Model_Product ();
		
		$categoryId = $this->_params ['id'];
		$parents = $this->_model->getParentProduct ( $categoryId );
		$products = $productModel->getProductByProductId ( $categoryId );
		
		if ($products != NULL) {
			$message = 'Không thể xoá danh mục này. Vì có sản phẩm trong danh mục';
			$message = $this->_helper->popupMessage ( $message );
			$result = array (
					'result' => 2,
					'value' => $message 
			);
		} elseif ($parents != NULL) {
			$message = 'Không thể xoá danh mục này. Vì có danh mục con';
			$message = $this->_helper->popupMessage ( $message );
			$result = array (
					'result' => 3,
					'value' => $message 
			);
		} else {
			$result = array (
					'result' => $this->_model->deleteItem ( $categoryId ),
					'value' => $categoryId 
			);
		}
		
		echo json_encode ( $result );
		die ();
	}
}